﻿//-----------------------------------------------------------------------
// <copyright file="UserController.cs" company="OOHM PROCESSAMENTO DE DADOS LTDA.">
//     Microsoft Public License (MS-PL) This license governs use of the accompanying
//     software. If you use the software, you accept this license. If you do not
//     accept the license, do not use the software. 1. Definitions The terms "reproduce,"
//     "reproduction," "derivative works," and "distribution" have the same meaning
//     here as under U.S. copyright law. A "contribution" is the original software,
//     or any additions or changes to the software. A "contributor" is any person
//     that distributes its contribution under this license. "Licensed patents"
//     are a contributor's patent claims that read directly on its contribution.
//     2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license,
//     including the license conditions and limitations in section 3, each contributor
//     grants you a non-exclusive, worldwide, royalty-free copyright license to
//     reproduce its contribution, prepare derivative works of its contribution,
//     and distribute its contribution or any derivative works that you create.
//     (B) Patent Grant- Subject to the terms of this license, including the license
//     conditions and limitations in section 3, each contributor grants you a non-exclusive,
//     worldwide, royalty-free license under its licensed patents to make, have
//     made, use, sell, offer for sale, import, and/or otherwise dispose of its
//     contribution in the software or derivative works of the contribution in
//     the software. 3. Conditions and Limitations (A) No Trademark License- This
//     license does not grant you rights to use any contributors' name, logo, or
//     trademarks. (B) If you bring a patent claim against any contributor over
//     patents that you claim are infringed by the software, your patent license
//     from such contributor to the software ends automatically. (C) If you distribute
//     any portion of the software, you must retain all copyright, patent, trademark,
//     and attribution notices that are present in the software. (D) If you distribute
//     any portion of the software in source code form, you may do so only under
//     this license by including a complete copy of this license with your distribution.
//     If you distribute any portion of the software in compiled or object code
//     form, you may only do so under a license that complies with this license.
//     (E) The software is licensed "as-is." You bear the risk of using it. The
//     contributors give no express warranties, guarantees or conditions. You may
//     have additional consumer rights under your local laws which this license
//     cannot change. To the extent permitted under your local laws, the contributors
//     exclude the implied warranties of merchantability, fitness for a particular
// </copyright>
//-----------------------------------------------------------------------
namespace AbstractSaaSTemplate.UI.Web.Controllers{    using System;
    using System.Collections.Generic;
    using System.Dynamic;
    using System.Globalization;
    using System.Web;
    using System.Web.Mvc;
    using AbstractSaaSTemplate.Application.Localization;
    using AbstractSaaSTemplate.Application.Mvc;
    using AbstractSaaSTemplate.Domain.Models.Entities;
    using AbstractSaaSTemplate.Domain.Models.Enumerators;
    using AbstractSaaSTemplate.Domain.Repositories;
    using AbstractSaaSTemplate.Domain.Services;
    using AbstractSaaSTemplate.UI.Web.Filters.Actions.Loaders;
    using AbstractSaaSTemplate.UI.Web.Filters.Actions.Security;
    using AbstractSaaSTemplate.UI.Web.Models.User;

    /// <summary>
    /// Provides HTTP processing logic for the conceptual entity 'User'
    /// in the 'Root' module of the application.
    /// </summary>
    public sealed class UserController : ApplicationController
    {
        /// <summary>
        /// Initializes a new instance of the UserController class
        /// injecting the services and repositories required for operation.
        /// </summary>
        /// <param name="serviceForMembership">The service to consume 'Memberships'.</param>
        /// <param name="repositoryForMembership">The repository to operate 'Memberships'.</param>
        public UserController(
            IMembershipService serviceForMembership,
            IMembershipRepository repositoryForMembership)
        {
            this.ServiceForMembership = serviceForMembership;
            this.RepositoryForMembership = repositoryForMembership;
        }

        /// <summary>
        /// Gets the service to consume 'Memberships'.
        /// </summary>
        public IMembershipService ServiceForMembership { get; private set; }

        /// <summary>
        /// Gets the repository to operate 'Memberships'.
        /// </summary>
        public IMembershipRepository RepositoryForMembership { get; private set; }

        /// <summary>
        /// GET: /User/LogOn
        /// Provides a page in which the user can provide credentials and
        /// is authenticated to use private functions of the service.
        /// </summary>
        /// <returns>Returns a View with a form for authentication.</returns>
        [HttpGet]
        public ActionResult LogOn()
        {
            return this.Result();
        }

        /// <summary>
        /// POST: /User/LogOn
        /// Process the user input and performs the LogOn
        /// in case the credentials in it are valid.
        /// </summary>
        /// <param name="input">The user input with the credentials.</param>
        /// <param name="returnUrl">The url for which the user should be redirected in case the credentials are valid.</param>
        /// <returns>Returns a View with an error in case not valid; otherwise, redirects the user authenticated to the Home > Index action.</returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOn(
            LogOnForm input,
            string returnUrl)
        {
            // we check the basic input and prevents null values for it
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            // we reinforce the model validation
            // this will ensure that the validation is performed
            // even when we are invoking this method from a unit test instead
            // of a HttpRequest.
            if (this.ModelState.IsValid)
            {
                this.TryValidateModel(input);
            }

            // we should validate all the data in the input argument
            // that could not be checked by the DataAnotations in the 'CreateOrEditForm'
            // add all errors using the this.ModelState.AddModelError() method

            /*
            this.ModelState.AddError(
                "Id",
                string.Format(
                    CultureInfo.CurrentCulture,
                    Messages.TheParameterXCannotBeNullOrWhiteSpace,
                    "Id"));
            */

            // we decide whether to proceed or not with the update operation
            // mostly by checking if the this.ModelState.IsValid
            if (this.ModelState.IsValid)
            {
                var logOn = this.ServiceForMembership.LogOn(
                        input.Login,
                        input.Password,
                        input.RememberMe);
                
                if (logOn)
                {
                    // it was successfull, so we redirect
                    // the user to "Home" > "Index"
                    if (Url.IsLocalUrl(returnUrl))
                    {
                        return this.Redirect(returnUrl);
                    }
                    else
                    {
                        return this.RedirectToAction(
                            "Index",
                            "Home");
                    }
                }
                else
                {
                    this.ModelState.AddModelError(
                        string.Empty,
                        Messages.NotPossibleToAuthenticate);
                }
            }

            // we didn't manage to perform the operations
            // therefore we must return the default result
            // with model state information which explains
            // why we couldn't proceed.
            return this.Result(input);
        }

        /// <summary>
        /// GET: /User/LogOff
        /// Process the LogOff action
        /// </summary>
        /// <returns>Redirects the user to Home > Index.</returns>
        [HttpGet]
        public ActionResult LogOff()
        {
            this.ServiceForMembership.LogOut();
            return this.RedirectToAction(
                "Index",
                "Home");
        }

        /// <summary>
        /// GET: /User/ChangePassword
        /// Provides a page in which the user can change his/her password.
        /// </summary>
        /// <returns>Returns a view containing the form to change credentials.</returns>
        [Authorize]
        [LoadPasswordLength]
        public ActionResult ChangePassword()
        {
            return this.Result();
        }

        /// <summary>
        /// POST: /User/ChangePassword
        /// Processes the user input and tries to change the user password
        /// which will only happen if the credentials are valid.
        /// </summary>
        /// <param name="input">The user input containing credentials and new password.</param>
        /// <returns>Returns a View with model state error if not valid; otherwise, redirects the user to User > ChangePasswordSuccess</returns>
        [Authorize]
        [HttpPost]
        [ValidateAntiForgeryToken]
        [LoadPasswordLength]
        public ActionResult ChangePassword(
            ChangePasswordForm input)
        {
            // we check the basic input and prevents null values for it
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            // we reinforce the model validation
            // this will ensure that the validation is performed
            // even when we are invoking this method from a unit test instead
            // of a HttpRequest.
            if (this.ModelState.IsValid)
            {
                this.TryValidateModel(input);
            }

            // we should validate all the data in the input argument
            // that could not be checked by the DataAnotations in the 'CreateOrEditForm'
            // add all errors using the this.ModelState.AddModelError() method

            /*
            this.ModelState.AddError(
                "Id",
                string.Format(
                    CultureInfo.CurrentCulture,
                    Messages.TheParameterXCannotBeNullOrWhiteSpace,
                    "Id"));
            */

            // we decide whether to proceed or not with the update operation
            // mostly by checking if the this.ModelState.IsValid
            if (this.ModelState.IsValid)
            {
                if (this.ServiceForMembership.ChangeCredentials(
                    User.Identity.Name,
                    input.OldPassword,
                    input.NewPassword))
                {
                    // it was successfull, so we redirect
                    // the user to "User" > "ChangePasswordSuccess"
                    return RedirectToAction(
                        "ChangePasswordSuccess");
                }
                else
                {
                    this.ModelState.AddModelError(
                        string.Empty,
                        "The current password is incorrect or the new password is invalid.");
                }
            }

            // we didn't manage to perform the operations
            // therefore we must return the default result
            // with model state information which explains
            // why we couldn't proceed.
            return this.Result(input);
        }

        /// <summary>
        /// GET: /User/ChangePasswordSuccess
        /// Provides a page with a confirmation message after a
        /// successful attempt to change the password.
        /// </summary>
        /// <returns>Returns a view with a success message.</returns>
        [HttpGet]
        public ActionResult ChangePasswordSuccess()
        {
            return this.Result();
        }

        /// <summary>
        /// GET: /User/ChangeCulture
        /// Provides functionality to change the culture
        /// </summary>
        /// <param name="currentControllerName">The current controller name, so that redirection happens to the same route.</param>
        /// <param name="currentActionName">The current action name, so that redirection happens to the same route.</param>
        /// <returns>Returns a partial view for users to change their culture.</returns>
        [HttpGet]
        [LoadCulturesAvailable]
        public ActionResult ChangeCulture(
            string currentControllerName,
            string currentActionName)
        {
            dynamic model = new ExpandoObject();
            model.Controller = currentControllerName;
            model.Action = currentActionName;

            return this.Result(model);
        }
        
        /// <summary>
        /// POST: /User/ChangeCulture
        /// Changes the culture for the current user and session.
        /// </summary>
        /// <param name="currentControllerName">The current controller name.</param>
        /// <param name="currentActionName">The current action name.</param>
        /// <param name="cultureName">The culture that is being set to the current session and account.</param>
        /// <returns>Returns a JsonResult with the resulted cultureName.</returns>
        [HttpPost]
        [LoadCulturesAvailable]
        public ActionResult ChangeCulture(
            string currentControllerName,
            string currentActionName,
            string cultureName)
        {
            // we check the basic input and prevents null values for it
            if (string.IsNullOrWhiteSpace(cultureName))
            {
                throw new ArgumentNullException("cultureName");
            }

            // we should validate all the data in the input argument
            // that could not be checked by the DataAnotations in the 'CreateOrEditForm'
            // add all errors using the this.ModelState.AddModelError() method

            // we decide whether to proceed or not with the update operation
            // mostly by checking if the this.ModelState.IsValid
            if (this.ModelState.IsValid)
            {
                var login = null as string;
                var activeUser = this.ServiceForMembership.ActiveUser;

                if (activeUser != null)
                {
                    login = activeUser.Credentials.Login;
                }
                
                this.ServiceForMembership.ChangeCulture(
                    login,
                    cultureName);
            }

            // set the default routing
            if (string.IsNullOrWhiteSpace(currentControllerName))
            {
                currentControllerName = "Home";
            }

            if (string.IsNullOrWhiteSpace(currentActionName))
            {
                currentActionName = "Index";
            }

            var redirectToRoute = Url.Action(
                currentActionName,
                currentControllerName);

            // we didn't manage to perform the operations
            // therefore we must return the default result
            // with model state information which explains
            // why we couldn't proceed.
            var currentLocation = this.Request.Url;
            return this.Json(new
            {
                CultureName = cultureName,
                RedirectTo = string.Concat(
                    currentLocation.Scheme,
                    Uri.SchemeDelimiter,
                    currentLocation.Authority,
                    VirtualPathUtility.ToAbsolute(redirectToRoute))
            });
        }

        /// <summary>
        /// GET: /User/ListUsers
        /// Provides a page in which the user can change his/her password.
        /// </summary>
        /// <returns>Returns a view containing the list of users.</returns>
        [HttpGet]
        [FeatureAuthorization(
            AccessLevels.Distributor | AccessLevels.Tenant | AccessLevels.Account,
            ControlledFeatures.UsersManagement,
            true)]
        public ActionResult ListUsers()
        {
            var activeUser = this.ServiceForMembership.ActiveUser;
            var level = activeUser.AccessLevel;

            var users = null as IEnumerable<User>;
            if (level == AccessLevels.Distributor)
            {
                users = this.RepositoryForMembership.GetUsers(level);
            }
            else
            {
                users = this.RepositoryForMembership.GetUsers(activeUser.Id, level);
            }

            return this.Result(users);
        }

        /// <summary>
        /// GET: /User/CreateOrEdit
        /// GET: /User/CreateOrEdit/5
        /// Provides a create/edit features for the 'User' section of the area.
        /// </summary>
        /// <param name="id">The id which is reference for the entry that you are entity; If null, will cause this action to create a new entry.</param>
        /// <returns>Returns a view containing a landing page</returns>
        [HttpGet]
        [FeatureAuthorization(
            AccessLevels.Distributor | AccessLevels.Tenant | AccessLevels.Account,
            ControlledFeatures.UsersManagement)]
        public ActionResult CreateOrEditUser(int? id)
        {
            var model = null as CreateOrEditUserForm;

            if (id.HasValue)
            {
                var entity = this.RepositoryForMembership.GetUserById(id.Value);
                if (entity != null)
                {
                    model = new CreateOrEditUserForm(AccessRoles.Operator);

                    model.FirstName = entity.FirstName;
                    model.LastName = entity.LastName;
                    model.EmailAddress = entity.EmailAddress;

                    model.Login = entity.Credentials.Login;
                    model.CultureName = entity.Culture.Name;

                    model.IsDisabled = entity.IsDisabled;
                }
            }

            if (model == null)
            {
                model = new CreateOrEditUserForm();
            }

            return this.Result(model);
        }

        /// <summary>
        /// POST: /User/CreateOrEdit
        /// POST: /User/CreateOrEdit/5
        /// Processes the user input and try to proceed with the creation or edition of the item.
        /// </summary>
        /// <param name="id">The id of the entry which you are editting; If null, will cause the creation of a new entry.</param>
        /// <param name="input">The user input parsed into a form (view model) which can be used for easier validation of this data.</param>
        /// <returns>If validation or procedure fails, returns a view with errors loaded into the ModelState; otherwise redirects the user to the action "Index"</returns>
        [HttpPost]
        [FeatureAuthorization(
            AccessLevels.Distributor | AccessLevels.Tenant | AccessLevels.Account,
            ControlledFeatures.UsersManagement)]
        [ValidateAntiForgeryToken]
        public ActionResult CreateOrEditUser(long? id, CreateOrEditUserForm input)
        {
            // we check the basic input and prevents null values for it
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            // we reinforce the model validation
            // this will ensure that the validation is performed
            // even when we are invoking this method from a unit test instead
            // of a HttpRequest.
            if (this.ModelState.IsValid)
            {
                this.TryValidateModel(input);
            }

            // we should validate all the data in the input argument
            // that could not be checked by the DataAnotations in the 'CreateOrEditForm'
            // add all errors using the this.ModelState.AddModelError() method

            /*
            this.ModelState.AddError(
                "Id",
                string.Format(
                    CultureInfo.CurrentCulture,
                    Messages.TheParameterXCannotBeNullOrWhiteSpace,
                    "Id"));
            */

            // we decide whether to proceed or not with the update operation
            // mostly by checking if the this.ModelState.IsValid
            if (this.ModelState.IsValid)
            {
                var entity = null as User;

                // some things are only performed when we are editting
                if (id.HasValue)
                {
                    // we load the entity, so whatever we change
                    // will update the existing information.
                    entity = this.RepositoryForMembership.GetUserById(id.Value);
                }
                
                // if not found, we create the entity
                if (entity == null)
                {
                    // we create the instance of user
                    entity = new User();

                    // the access level is the same as the user who
                    // is creating the user and only if the user is new.
                    var activeUser = this.ServiceForMembership.ActiveUser;
                    entity.AccessLevel = activeUser.AccessLevel;
                }

                entity.FirstName = input.FirstName;
                entity.LastName = input.LastName;
                entity.EmailAddress = input.EmailAddress;
                entity.IsDisabled = input.IsDisabled;

                if (string.IsNullOrWhiteSpace(input.CultureName))
                {
                    entity.Culture = CultureInfo.CurrentUICulture;
                }
                else
                {
                    entity.Culture = CultureInfo.GetCultureInfo(input.CultureName);
                }

                entity.Credentials.Login = input.Login;
                entity.Credentials.SetPassword(input.Password);

                // we save the info into the repository
                this.RepositoryForMembership.AddOrUpdateUser(entity);

                // it was successfull, so we redirect
                // the user to "User" > "Index"
                return this.RedirectToAction("ListUsers");
            }

            // we didn't manage to perform the operations
            // therefore we must return the default result
            // with model state information which explains
            // why we couldn't proceed.
            return this.Result(input);
        }
    }
}


